﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;

namespace WSS.Web
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //使代码压缩(js,css)
            //BundleTable.EnableOptimizations = true;

            WSS.Pub.Init.InitDao();

            // 在应用程序启动时运行的代码  
            System.Timers.Timer my_timer = new System.Timers.Timer();
            my_timer.Elapsed += new System.Timers.ElapsedEventHandler(CleanOnlineAccountCache);
            my_timer.Interval = 10 * 60 * 1000;//10minuts
            my_timer.Enabled = true;
        }

        protected void Application_AuthenticateRequest()
        {
            string cookie_name = FormsAuthentication.FormsCookieName;//从验证票据获取Cookie的名字。

            //取得Cookie.
            HttpCookie auth_cookie = Context.Request.Cookies[cookie_name];
            if (null == auth_cookie)
            {
                return;
            }

            if (!auth_cookie.HasKeys)
            {
                return;
            }

            //获取验证票据。 
            FormsAuthenticationTicket auth_ticket = FormsAuthentication.Decrypt(auth_cookie.Value);
            if (null == auth_ticket)
            {
                return;
            }

            //验证票据的UserData中存放的是用户角色信息。
            //UserData本来存放用户自定义信息。此处用来存放用户角色。
            string[] roles = auth_ticket.UserData.Split(new[] { ',' });
            FormsIdentity id = new FormsIdentity(auth_ticket);
            GenericPrincipal principal = new GenericPrincipal(id, roles);
            //把生成的验证票信息和角色信息赋给当前用户．
            Context.User = principal;
        }


        /// <summary>
        /// 定时器定时执行清除在线超时用户
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private static void CleanOnlineAccountCache(object source, System.Timers.ElapsedEventArgs e)
        {
            //间隔时间执行某动作  
            WSS.BLL.Account.UserOnline.RemoveOuttimeOnline();
        }
    }
}